from rest_framework import serializers
from ..models.GlobalTables import *

class GlobalTableListQuerySerializer(serializers.Serializer):
    name = serializers.CharField(required=False,allow_blank=True)
    zh_name = serializers.CharField(required=False,allow_blank=True)
    
    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False,allow_blank=True)
    sort_order = serializers.CharField(required=False,allow_blank=True)
    
    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "name" in attrs:
            attrs["name"] = attrs["name"].strip()
            if attrs["name"] == "": attrs.pop("name")
        if "zh_name" in attrs:
            attrs["zh_name"] = attrs["zh_name"].strip()
            if attrs["zh_name"] == "": attrs.pop("zh_name")  
        if ("name" not in attrs or attrs["name"] == "") and ("zh_name" not in attrs or attrs["zh_name"] == ""):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title":"名称：", "dataIndex":"name", "type":"CharField"},
                {"title":"中文名：", "dataIndex":"zh_name", "type":"CharField"},]
        
    
class GlobalTableListConfigSerializer(serializers.ModelSerializer):
    class Meta:
        model = Language 
        fields = ['uuid', 'name', 'zh_name']